package com.jielihaofeng.atguigu.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * @author Johnnie Wind
 * @description 群聊服务端
 * @date 2021/11/25 16:32
 */
public class GroupChatServer {
    private static final int PORT = 6667;
    // 定义属性
    private Selector selector;
    private ServerSocketChannel listenChannel;

    public GroupChatServer() {
        try {
            // 得到选择器
            selector = Selector.open();
            // ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            // 绑定端口
            listenChannel.bind(new InetSocketAddress(PORT));
            // 非阻塞模式
            listenChannel.configureBlocking(false);
            // 将该listenChannel注册到 selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        // 启动服务端
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }

    // 监听
    public void listen() {
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {
                    // 有事件处理
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();

                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                            // 给出提示
                            System.out.println(sc.getRemoteAddress() + " 上线 ");
                        }

                        if (key.isReadable()) {
                            // 读事件
                            readData(key);
                        }

                        // 删除key，防止重复处理
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待....");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    // 读取客户端消息
    public void readData(SelectionKey key) {

        SocketChannel channel = null;
        try {
            channel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if (count > 0) {
                // 读取到数据了，输出
                String mes = new String(buffer.array());
                System.out.println("from 客户端：" + mes);

                // 向其他客户端转发消息
                sendInfoToOtherClient(mes, channel);
            }

        } catch (Exception e) {
            try {
                System.out.println(channel.getRemoteAddress() + " 离线了...");
                // 取消注册
                key.cancel();
                // 关闭通道
                channel.close();
            } catch (IOException e2) {
                e2.printStackTrace();
            }
        }
    }

    // 转发消息给其他通道
    private void sendInfoToOtherClient(String msg, SocketChannel self) throws IOException {

        System.out.println("服务器转发消息中...");
        // 遍历所有注册到selector上的 SocketChannel，并排除 self
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel();
            // 判断是客户端通道SocketChannel，并且不是自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                // 转型
                SocketChannel dest = (SocketChannel) targetChannel;
                // 获取消息Bytebuffer
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                // 写入消息
                dest.write(buffer);
            }
        }
    }
}
